package com.zoffy.oj_backend.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.zoffy.oj_backend.judge.codesandbox.model.JudgeInfo;
import com.zoffy.oj_backend.model.dto.question.JudgeCase;
import com.zoffy.oj_backend.model.dto.question.JudgeConfig;
import com.zoffy.oj_backend.model.enums.JudgeInfoMessageEnum;

import java.util.List;
import java.util.Optional;

public class DefaultJudgeJudgeStrategy implements JudgeStrategy {
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        JudgeInfo contextJudgeInfo = judgeContext.getJudgeInfo();
        long memory = Optional.ofNullable(contextJudgeInfo.getMemory()).orElse(0L);
        long time = Optional.ofNullable(contextJudgeInfo.getMemory()).orElse(0L);
        List<String> outputList = judgeContext.getOutputList();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        JudgeInfoMessageEnum judgeInfoMessageEnum = JudgeInfoMessageEnum.ACCEPTED;
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeContext.getQuestion().getJudgeConfig(), JudgeConfig.class);
        JudgeInfo judgeInfo = new JudgeInfo();


        if (outputList.size() != judgeCaseList.size()) {
            judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
            judgeInfo.setMessage(judgeInfoMessageEnum.getText());
            return judgeInfo;
        }
        long needMemoryLimit = judgeConfig.getMemoryLimit();
        long needTimeLimit = judgeConfig.getTimeLimit();
        if (memory > needMemoryLimit) {
            judgeInfoMessageEnum = JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
            judgeInfo.setMessage(judgeInfoMessageEnum.getText());
            return judgeInfo;
        }
        if (time > needTimeLimit) {
            judgeInfoMessageEnum = JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED;
            judgeInfo.setMessage(judgeInfoMessageEnum.getText());
            return judgeInfo;
        }


        for (int i = 0; i < outputList.size(); i++) {
            JudgeCase judgeCase = judgeCaseList.get(i);
            if (!judgeCase.getOutput().equals(outputList.get(i))) {
                judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
                judgeInfo.setMessage(judgeInfoMessageEnum.getText());
                return judgeInfo;
            }
        }
        judgeInfo.setMessage(judgeInfoMessageEnum.getText());
        judgeInfo.setTime(time);
        judgeInfo.setMemory(memory);
        return judgeInfo;
    }
}
